﻿@{
    Layout = "~/Shared/_SiteLayout.cshtml";
    Page.Title = "Register an account";

    string email = "";

    // Add Validation scripts
@*   @Scripts.Add("~/Scripts/jquery-1.6.2.min.js");
    Scripts.Add("~/Scripts/jquery.validate.min.js");
    Scripts.Add("~/Scripts/jquery.validate.unobtrusive.min.js");*@

    Validation.RequireField("email", "Username cannot be empty.");

    if (IsPost)
    {
        var result = (WebMatrix.Security.AuthenticationResult)Session["OAuthResult"];
        if (result == null)
        {
            Response.Redirect("~/");
        }

        email = Request.Form["email"];

        if (Validation.IsValid())
        {
            // Insert a new user into the database
            var db = DBObject.Open();

            // Check if user already exists
            var user = db.QuerySingle("SELECT Email FROM UserProfile WHERE LOWER(Email) = LOWER(@0)", email);
            if (user == null)
            {
                // Insert email into the profile table
                db.Execute("INSERT INTO UserProfile (Email) VALUES (@0)", email);
                AuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, email);

                AuthWebSecurity.Login(result.Provider, result.ProviderUserId);

                // mark the user as logged in via an OAuth or OpenID provider,
                // as opposed to via a normal account.
                Session["OAuthLoggedIn"] = true;

                Response.Redirect("~/");
            }
            else
            {
                ModelState.AddError("email", "This username is already taken.");

            }
        }
    }
    else
    {
        var result = AuthWebSecurity.VerifyAuthentication();
        if (result.IsSuccessful)
        {
            // put the ExtraData into the App property bag
            if (result.ExtraData != null && result.ExtraData.Count> 0)
            {
                Session.Add("OAuthExtraData", result.ExtraData);
            }

            bool registered = AuthWebSecurity.Login(result.Provider, result.ProviderUserId);
            if (registered)
            {
                // mark the user as logged in via an OAuth or OpenID provider,
                // as opposed to via a normal account.
                Session["OAuthLoggedIn"] = true;

                var returnUrl = Request.QueryString["ReturnUrl"];
                if (returnUrl.IsEmpty())
                {
                    Response.Redirect("~/");
                }
                else
                {
                    Context.RedirectLocal(returnUrl);
                }
            }
            else
            {
                Session["OAuthResult"] = result;
            }
            // set default username to the value obtained from OAuth
            email = result.UserName;
        }
        else
        {
            ModelState.AddFormError("Unsuccessful login with service.");
        }
    }
}
<hgroup class="title">
    <h1>Register.</h1>
    <h2>Create an account on this site to associate to this service. </h2>
</hgroup>
<form action="" method="post">
@* If at least one validation error exists, notify the user *@
@Html.ValidationSummary()
<fieldset>
    <legend>Registration Form</legend>
    <ol>
        <li class="email">
            <label for="email" @if (!ModelState.IsValidField("email"))
                               {<text>class="error-label"</text>}>
                Email:</label>
            <input type="text" id="email" name="email" title="Email address" value="@email" @Validation.For("email") />
            @* Write any email validation errors to the page *@
            @Html.ValidationMessage("email")
        </li>
    </ol>
    <input type="submit" value="Associate" title="Associate" />
</fieldset>
</form>